package org.duiduo.common.runtime.xss;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.duiduo.common.runtime.util.HttpContextUtil;
import org.duiduo.common.runtime.util.XssUtil;
import org.springframework.util.PathMatcher;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

/**
 * XSS json过滤
 *
 * @author liangze
 * @date 2025/9/4 17:29
 */
@AllArgsConstructor
public class XssFilterJsonDeserializer extends JsonDeserializer<String> {

    private final XssProperties properties;
    private final PathMatcher pathMatcher;

    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        String value = jsonParser.getValueAsString();
        if (StrUtil.isBlank(value)) {
            return value;
        }
        HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
        if (request == null) {
            return value;
        }
        // 判断该URI是否放行
        boolean flag = properties.getExcludeUrls().stream()
                .anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, request.getServletPath()));
        if (flag) {
            return value;
        }
        return XssUtil.filter(value);
    }

    @Override
    public Class<String> handledType() {
        return String.class;
    }
}
